<template>
    <el-upload
        drag
        accept="imageTypes"
        :list-type="listType" :show-file-list="showFileList" :limit="maxCount"
        :file-list="fileList"
        :http-request="uploadRequest"
        :multiple="true"
        :on-exceed="handleExceed"
        :before-upload="handleBeforeUpload"
    >
        <el-icon size="100" color="gray">
            <UploadFilled/>
        </el-icon>
        <div class="el-upload__tip" slot="tip">支持3D格式： stl/gltf/obj ， 单次上传文件 ≤20 个，单个文件大小 <
            100M ，文件名（含后缀）不超过50个字符
        </div>
        <div class="el-upload__tip" slot="tip" style="color:red;">
            注：为了更准确打印以及避免不必要的纠纷，强烈建议上传STL格式文件！
        </div>
        <div class="el-upload__tip" slot="tip">特别提醒：壁厚需大于1.2mm，薄处不低于0.8mm</div>
    </el-upload>

</template>

<script setup>
import {computed} from "vue";
import {UploadFilled} from "@element-plus/icons-vue";
import {getUploadPresigned, uploadByPresignedUrl} from "@/apis/file.js";

const props = defineProps({
    modelValue: {
        type: Array,
        default: []
    },
    maxCount: {
        type: Number,
        default: 5
    },
    listType: {
        type: String,
        default: "text"
    },
    showFileList: {
        type: Boolean,
        default: true
    }
})
const emits = defineEmits(["update:modelValue"])
const fileList = computed(() => props.modelValue)

const handleExceed = () => {
    ElMessage.warning(`最多只能上传${props.maxCount}个模型文件`)
}
/**
 * 限制用户上传文件的格式和大小
 */
const handleBeforeUpload = rawFile => {
    let flag = checkSuffix(rawFile.name)
    if (!flag) {
        ElMessage.error("很抱歉您上传的不是stl/gltf/obj格式");
        return false;
    } else if (rawFile.size / 1024 / 1024 > 100) {
        ElMessage.error("您上传的模型大小超过了100MB");
        return false;
    }
    //获取预签名URL
    getUploadPresigned(rawFile.name).then(({data}) => {
        //根据预签名URL上传文件
        uploadByPresignedUrl(data, rawFile).then(() => {
            emits("update:modelValue", [...props.modelValue, {model: data.slice(0, data.indexOf("?")), quantity: 1}])
            ElMessage.success("上传成功")
        })
    })
}

/**
 *  自定义上传函数替换掉原来的处理逻辑，防止根据action上传报错而无法回显fileList
 */
const uploadRequest = () => {
}

function checkSuffix(str) {
    let strRegex = /\.(stl|gltf|obj)$/;
    return strRegex.test(str.toLowerCase());
}
</script>

<style scoped lang="scss">
.upload-preview {
    padding: 0 5em 0 5em;
}

.dialog-footer {
    display: flex;
    justify-content: space-between;
}
</style>
